<template>
  <div class="ju-overflow-auto px-1 overflow-auto"
       :class="{'is-show-overflow rounded-1 border py-1':isShowOverflow}"
       :style="{maxHeight}">
    <slot></slot>
    <!-- 不给宽度就不会触发宽度变化时产生的resize -->
    <iframe v-if="maxHeight"
            seamless
            style="top:0;left:0;width:1px;height:100%;position:absolute;z-index:-1;border:none;box-sizing:border-box;visibility:hidden;opacity:0;pointer-events:none"
            @load="bindIframeResize"></iframe>
  </div>
</template>

<script lang="ts">
  import { Component, Prop, Vue } from "@some21/vue-class-decorator";
  import { debounce } from "lodash";

  @Component({
    name: "ju-overflow-auto",
  })
  export default class extends Vue {
    @Prop({ type: Number })
    maxHeight: number;

    isShowOverflow = false;

    bindIframeResize(evt) {
      const iframeElm = evt.target;
      const parentElm = evt.target.parentElement;
      const onHeightChange = debounce(async () => {
        await Vue.nextTick();
        const { height: iframeHeight } = iframeElm.getBoundingClientRect(); // 获取更精准的高度
        // console.log(parentElm, iframeElm, parentElm.scrollHeight, Math.ceil(iframeHeight));
        // parentElm.scrollHeight 的值会自动向上取整，所以判断时 iframeHeight 也需要 向上取整
        this.isShowOverflow = parentElm.scrollHeight > Math.ceil(iframeHeight);
      }, 100); // 当设置为 50 时，由于动画原因，高度获取会存在异常

      (evt.target.contentWindow as Window).addEventListener("resize", onHeightChange);
    }
  }
</script>

<style lang="scss" scoped>
  .ju-overflow-auto {
    position: relative;
    white-space: pre-line;
  }
</style>
